// Learn TypeScript:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/2.4/manual/en/scripting/life-cycle-callbacks.html

import ComponentBase from "../../general/Script/component/ComponentBase";
import GameMgr from "../../general/Script/mgr/gameManager";
import NativeMgr from "../../general/Script/mgr/nativeManager";
import SoundMgr from "../../general/Script/mgr/soundManager";
import { MainHotUpdate } from "../../general/Script/update/MainHotUpdate";
import { Game_Const } from "../../general/Script/update/ManifestInfo";



const { ccclass, property } = cc._decorator;

@ccclass
export default class Launch extends ComponentBase {
    progress: cc.Node
    persistRootNode: cc.Node
    // LIFE-CYCLE CALLBACKS:
    canStart: boolean = false;
    loginServer: boolean = false;

    @property(cc.Prefab)
    msgLayer: cc.Prefab = null;

    @property(cc.Prefab)
    loadingLayer: cc.Prefab = null;

    onLoad() {
        super.onLoad()



    }

    async start() {
        if (await this.isSettSearchPaths()) {
            console.log("isSettSearchPaths");
            cc.game.restart();
            return;
        }
        if (this.isClearHotUpdateDir()) {
            console.log("isClearHotUpdateDir");
            cc.game.restart();
            return;
        }


        // const block = cc.find('Canvas/block')
        // cc.game.addPersistRootNode(block)

        // const msgNode = cc.find('Canvas/msgNode')
        // cc.game.addPersistRootNode(msgNode)

        // GameMgr.Ins().blockNode = block;
        // GameMgr.Ins().msgNode = block;


        const loadingLayer = cc.instantiate(this.loadingLayer);

        loadingLayer.active = false;
        loadingLayer.parent = cc.director.getScene()
        loadingLayer.x = cc.winSize.width / 2;
        loadingLayer.y = cc.winSize.height / 2;
        GameMgr.Ins().loadingNode = loadingLayer;
        cc.game.addPersistRootNode(loadingLayer)


        const msgNode = cc.instantiate(this.msgLayer);

        msgNode.active = false;
        msgNode.parent = cc.director.getScene()
        msgNode.x = cc.winSize.width / 2;
        msgNode.y = cc.winSize.height / 2;
        GameMgr.Ins().msgNode = msgNode;
        cc.game.addPersistRootNode(msgNode)

        const perNode = cc.find('Canvas/persistRootNode')
        perNode.parent = cc.director.getScene()
        cc.game.addPersistRootNode(perNode)






        // this.initNativeMsg();


        SoundMgr.Ins().initSound();


        const location = NativeMgr.Ins().updateLocation();

        if (location == '0') {
            GameMgr.Ins().showMsg('请打开定位', "关闭游戏", "继续游戏", () => {
                cc.game.end();
            })
        }


        cc.director.loadScene('update');

    }


    /**
    * 是否设置过索引
    *
    * 未设置过需要手动设置，否则不含在主包内的子游戏，下载后将无法启动
    */
    async isSettSearchPaths() {
        if (!CC_JSB) {
            // 非原生跳过
            return false;
        }
        let hotUpdateSearchPaths = <any>localStorage.getItem("HotUpdateSearchPaths");
        if (!hotUpdateSearchPaths) {
            let storagePath = jsb.fileUtils.getWritablePath() + "game-remote-asset/";
            let searchPath = storagePath + "assets/";
            jsb.fileUtils.createDirectory(storagePath);
            jsb.fileUtils.createDirectory(searchPath);
            try {
                let mianHotUpdateCtrl = new MainHotUpdate();
                let manifest = await mianHotUpdateCtrl.loadManifest(storagePath);
                jsb.fileUtils.writeStringToFile(manifest["_nativeAsset"], storagePath + "project.manifest");
                let searchPaths = [storagePath, searchPath, "@assets/"];
                cc.sys.localStorage.setItem("HotUpdateSearchPaths", JSON.stringify(searchPaths));
                jsb.fileUtils.setSearchPaths(searchPaths);
                return true;
            } catch (error) {
                return false;
            }
        }
        return false;
    }

    /**
     * 是否清除热更文件夹
     *
     * apk版本与热更后保存apk版本不一致时需要清除上一个apk版本遗留下的热更文件
     *
     * 清除后会自动重启
     * @returns
     */
    isClearHotUpdateDir(): boolean {
        if (!CC_JSB) {
            // 非原生跳过
            return false;
        }
        let hotUpdateAppVer = cc.sys.localStorage.getItem("HotUpdateSucceedAppVer");
        if (hotUpdateAppVer) {
            if (hotUpdateAppVer != Game_Const.native_version) {
                // 版本不对 清空热更目录的数据 重启
                console.log("cleaning up old data...");
                let storagePath = jsb.fileUtils.getWritablePath() + "game-remote-asset";
                jsb.fileUtils.removeDirectory(storagePath);
                cc.audioEngine.stopAll();
                cc.sys.localStorage.removeItem("HotUpdateSucceedAppVer");
                return true;
            }
        }
        return false;
    }


    initNativeMsg() {

        // GameMgr.Ins().nativeMsg('openAdsOver',(data)=>{
        //     console.log('开屏动画结束---',data);
        //     this.loadScene()
        // },this)

        // this.scheduleOnce(()=>{
        //     console.log('开屏动画加载失败---');
        //     this.loadScene()
        // },10)


        this.loadScene()
    }





    loadScene() {
        this.progress.active = true;
        cc.director.preloadScene('scene', (progress, total) => {
            this.progress.getComponent(cc.ProgressBar).progress = progress / total;
            if (progress == total) {
                cc.log('场景预加载成功：', progress, total);


                //跟上面二选一
                cc.director.loadScene("scene");
                // NativeMgr.Ins().showBottomBannerAds(true);
            }

        }, function (error) {
            cc.error('场景预加载失败：' + error);
        });
    }
    onDestroy(): void {


    }

}
